package servlets.user;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import external.EmailUtility;

/**
 * Servlet implementation class Contact
 */
@WebServlet("/Contact")
public class Contact extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String host;
	private String port;
	private String user;
	private String pass;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Contact() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() {
		// reads SMTP server setting from web.xml file
		ServletContext context = getServletContext();
		host = context.getInitParameter("host");
		port = context.getInitParameter("port");
		user = context.getInitParameter("user");
		pass = context.getInitParameter("pass");
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String recipient = (String) request.getParameter("email");
		String subject = (String) request.getParameter("subject");
		String message = (String) request.getParameter("message");
		String message1 = EmailUtility.sendContactMail(recipient, subject, message);
 
        try {
        	EmailUtility.sendContactEmail(host, port, user, pass, recipient, user, subject, message1);
        	out.println("<script type=\"text/javascript\">alert(\"Dziekujemy za wypelnienie formularza\"); window.location.href = \"index.jsp?page=contact\";</script>");
    		
        } catch (Exception ex) {
            ex.printStackTrace();
            out.println("<script type=\"text/javascript\">alert(\"Wystapil nieznany blad. Za utrudnienia przepraszamy\"); window.location.href = \"index.jsp?page=contact\";</script>");
    		
        } 
    }

	}


